import axios from 'axios';
import {tool} from './tool.js';
import router from './router.js';
import {apiPrefix} from './config.js';

const service = axios.create({
    timeout: 15000 // 请求超时时间
});

service.interceptors.request.use(config => {
    config.headers['authorization'] = tool.getCookie('token');
    config.url = apiPrefix + config.url;
    config.method = config.method || 'get';
    config.data = !!config.data ? config.data : config.params;
    return config;
}, error => {
    return Promise.reject(error);
});

service.interceptors.response.use(
    (res) => {
        if (res.status === 200) {
            if (res.data.code === 200) {
                return res.data;
            } else {
                tool.message(res.data.msg, 'error');
                return Promise.reject(res.data);
            }
        } else {
            tool.message(res.data.msg, 'error');
            return Promise.reject(res.data);
        }
    },
    (error) => {
        let r = error.response;
        // console.log(r.status);
        switch (r.status) {
            case 403:
                tool.message(r.data.msg, 'error', () => {
                    setTimeout(() => {
                        router.push({path: '/login'});
                    }, 1000);
                });
                break;
            default:
                tool.message(r.data.msg, 'error');
        }
        return Promise.reject(error);
    }
);

export default service;
